﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using RCREEE.Library.Entities;

namespace RCREEE.Web
{
    public partial class EnergyConsumptionDevelopmentSettings : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                //// Add the language code to session
                //Session.Add("LanguageCode", 1033);

                // Get all master Energy Consumptions Development items
                EnergyConsumptionDevelopmentItemValue _energy = new EnergyConsumptionDevelopmentItemValue();
                int LanguageCode = Convert.ToInt32(Session["LanguageCode"]);
                DataTable dtEnergyConsumptionItems = _energy.GetAllMasterEnergyConsumptions(LanguageCode, 0);

                // Add contacts datatable to the current session
                Session.Add("dtEnergyConsumptionItems", dtEnergyConsumptionItems);

                // Bulid the items Tree
                BuildTree(tvMasterItems, 0);
            }

        }

        /// <summary>
        /// Fill The tree nodes with Items From dtEnergyConsumptionDevelopment
        /// </summary>
        /// <param name="ItemsTree">Name of TreeView Control to be built</param>
        private void BuildTree(TreeView ItemsTree, int ExceptionItemId)
        {
            // Refresh data if table in session is null
            if (Session["dtEnergyConsumptionItems"] == null)
                RefreshEnergyConsumptionMasterTable(ExceptionItemId);

            ItemsTree.Nodes.Clear();

            // Get All Parent Items
            DataRow[] currentRows = ((DataTable)Session["dtEnergyConsumptionItems"]).Select("ParentItemId = 0");
            if (currentRows.Length > 0)
            {
                // Loop Through the parent Items
                foreach (DataRow dr in currentRows)
                {
                    // Create node
                    TreeNode parentNode = new TreeNode(dr["ItemName"].ToString(), dr["ItemId"].ToString());

                    // Get children nodes for the current node if exist
                    List<TreeNode> childNodes = GetChildren(Convert.ToInt32(dr["ItemId"]));

                    // if childrenNodes exists
                    if (childNodes != null)

                        // Add children nodes to the parent
                        foreach (TreeNode childNode in childNodes)
                            parentNode.ChildNodes.Add(childNode);

                    // Add the node to the tree
                    ItemsTree.Nodes.Add(parentNode);
                }
            }
        }

        /// <summary>
        /// Gets All Children related to a specifec Parent (Item Id)
        /// </summary>
        /// <param name="currentItemId">Id of the ParentItem to get its children</param>
        /// <returns>List of TreeNodes related to the current Parent Item, NULL if it has no children</returns>
        private List<TreeNode> GetChildren(int currentItemId)
        {
            // refresh data if table in session is null
            if (Session["dtEnergyConsumptionItems"] == null)
                RefreshEnergyConsumptionMasterTable(0);

            // Get all children nodes for the current parent
            DataRow[] currentRows = ((DataTable)Session["dtEnergyConsumptionItems"]).Select("ParentItemId = " + currentItemId);

            // if xhildren exist
            if (currentRows.Length > 0)
            {
                //create a temp List of tree nodes
                List<TreeNode> tempChildNodes = new List<TreeNode>();
                foreach (DataRow dr in currentRows)
                {
                    // create a Tree node to hold the current child
                    TreeNode node = new TreeNode(dr["ItemName"].ToString(), dr["ItemId"].ToString());

                    // get children nodes of the current Child Node 
                    List<TreeNode> childNodes = GetChildren(Convert.ToInt32(dr["ItemId"]));
                    // if children exist ... add them to the current child
                    if (childNodes != null)
                        foreach (TreeNode childNode in childNodes)
                            node.ChildNodes.Add(childNode);

                    // add the current child node to the temp list
                    tempChildNodes.Add(node);
                }
                // return the temp list
                return tempChildNodes;
            }
            else
                // return null .. as no children exist
                return null;
        }

        /// <summary>
        /// Refresh The Table EnergyConsumptionMaster with all Items from database, and reinsert it in the session object
        /// </summary>
        /// <param name="ExceptionItemId"> Item Id to be excluded form the table</param>
        private void RefreshEnergyConsumptionMasterTable(int ExceptionItemId)
        {
            int LanguageCode = Convert.ToInt32(Session["LanguageCode"]);
            DataTable dtEnergyConsumptionItems = new DataTable();
            EnergyConsumptionDevelopmentItemValue _energy = new EnergyConsumptionDevelopmentItemValue();

            // Get All Energy Items data for database
            dtEnergyConsumptionItems = _energy.GetAllMasterEnergyConsumptions(LanguageCode, ExceptionItemId);

            // Remove table form the session object
            Session.Remove("dtEnergyConsumptionItems");

            // Add Eneregy consumption datatable to the current session
            Session.Add("dtEnergyConsumptionItems", dtEnergyConsumptionItems);
        }

        /// <summary>
        /// Search all nodes exist in the given tree for a given value, if found Set node as SELECTED
        /// </summary>
        /// <param name="_tree">TreeView name to search in</param>
        /// <param name="searchValueparam"> Search Value (ParentItemId)</parm>
        private void SetTreeSelectedNode(TreeView _tree, string searchValue)
        {
            // Loop throughall tree nodes
            foreach (TreeNode node in _tree.Nodes)
            {
                // If Value of the current node equals the search value
                if (node.Value == searchValue)
                {
                    // Set the current node as selected
                    node.Select();
                    break;
                }
                else
                {
                    // If the current node has children
                    if (node.ChildNodes.Count > 0)
                        // Perform a recursive search through the children of the current node
                        SearchRecursive(node, searchValue);
                }
            }
        }

        /// <summary>
        /// Search the current tree node and its children for a specific Value, set as selected node if FOUND
        /// </summary>
        /// <param name="node">Tree Node name</param>
        /// <param name="searchValue">Search Value (ParentItemId)</param>
        private void SearchRecursive(TreeNode node, string searchValue)
        {
            // Loop through The children of the current node
            foreach (TreeNode childNode in node.ChildNodes)
            {
                // check if the current node value equals the search value
                if (childNode.Value == searchValue)
                {
                    // set the current node as selected
                    childNode.Select();
                    break;
                }
                else
                    // if the current node has children
                    if (childNode.ChildNodes.Count > 0)
                        // perform a recursive search through the children of the current child node
                        SearchRecursive(childNode, searchValue);
            }

        }

        protected void btnClearParent_Click(object sender, EventArgs e)
        {
            if (((TreeView)fvMasterEnergyConsumptions.FindControl("tvParentItems_Edit")).SelectedNode != null)
            {
                // Clear "tvParentItems_Edit" tree view selection
                ((TreeView)fvMasterEnergyConsumptions.FindControl("tvParentItems_Edit")).SelectedNode.Selected = false;
                ((Label)fvMasterEnergyConsumptions.FindControl("lblParentItem_Edit")).Text = "";
            }
        }

        protected void btnClearParent_Insert_Click(object sender, EventArgs e)
        {
            if (((TreeView)fvMasterEnergyConsumptions.FindControl("tvParentItems_Insert")).SelectedNode != null)
            {
                // Clear "tvParentItems_Insert" tree view selection
                ((TreeView)fvMasterEnergyConsumptions.FindControl("tvParentItems_Insert")).SelectedNode.Selected = false;
                ((Label)fvMasterEnergyConsumptions.FindControl("lblParentItemName_Insert")).Text = "";
            }
        }

        protected void fvMasterEnergyConsumptions_DataBound(object sender, EventArgs e)
        {
            // Edit mode
            if (fvMasterEnergyConsumptions.CurrentMode == FormViewMode.Edit)
            {
                // get the current Item Id
                int currentItemId = Convert.ToInt32(((Label)fvMasterEnergyConsumptions.FindControl("lblItemIdValue_Edit")).Text);

                // Get all Items excluding the current Item Id ... to be excluded from the parent Items
                RefreshEnergyConsumptionMasterTable(currentItemId);

                // Build the parent tree view
                BuildTree(((TreeView)fvMasterEnergyConsumptions.FindControl("tvParentItems_Edit")), currentItemId);

                // Expand all tree nodes
                ((TreeView)fvMasterEnergyConsumptions.FindControl("tvParentItems_Edit")).ExpandAll();

                // If the current Item has a parent Item
                if (((Label)fvMasterEnergyConsumptions.FindControl("lblParentItemId_Edit")).Text != "0")
                {
                    // set The parent Item node as SELECTED
                    SetTreeSelectedNode(((TreeView)fvMasterEnergyConsumptions.FindControl("tvParentItems_Edit")),
                        ((Label)fvMasterEnergyConsumptions.FindControl("lblParentItemId_Edit")).Text);
                }

            }
            // Insert Mode
            else if (fvMasterEnergyConsumptions.CurrentMode == FormViewMode.Insert)
            {
                // Refresh the Items Table with Items form database
                RefreshEnergyConsumptionMasterTable(0);
                // Build the Parent Items Tree
                BuildTree(((TreeView)fvMasterEnergyConsumptions.FindControl("tvParentItems_Insert")), 0);

                // Expand all tree nodes
                ((TreeView)fvMasterEnergyConsumptions.FindControl("tvParentItems_Insert")).ExpandAll();

                // if an Item form the MASTER tree view is selected
                if (hiddenSelectedNodeId.Value != "")
                    // Set Parent Item as SELECTED by default
                    SetTreeSelectedNode(((TreeView)fvMasterEnergyConsumptions.FindControl("tvParentItems_Insert")), hiddenSelectedNodeId.Value);
            }
            else
            {
                int LanguageCode = Convert.ToInt32(Session["languageCode"]);

                switch (LanguageCode)
                {
                    case 1033:
                        {
                            try
                            {
                                ((Panel)fvMasterEnergyConsumptions.FindControl("pnlEnglishItemTemplate")).Visible = true;
                                ((Panel)fvMasterEnergyConsumptions.FindControl("pnlFrenchItemTemplate")).Visible = false;
                                ((Panel)fvMasterEnergyConsumptions.FindControl("pnlArabicDescription")).Visible = false;

                            }
                            catch (Exception exp)
                            {
                            }

                            break;
                        }
                    case 1036:
                        {
                            try
                            {
                                ((Panel)fvMasterEnergyConsumptions.FindControl("pnlEnglishItemTemplate")).Visible = false;
                                ((Panel)fvMasterEnergyConsumptions.FindControl("pnlFrenchItemTemplate")).Visible = true;
                                ((Panel)fvMasterEnergyConsumptions.FindControl("pnlArabicDescription")).Visible = false;

                            }
                            catch (Exception exp)
                            {
                            }

                            break;
                        }
                    case 1025:
                        {
                            try
                            {
                                ((Panel)fvMasterEnergyConsumptions.FindControl("pnlEnglishItemTemplate")).Visible = false;
                                ((Panel)fvMasterEnergyConsumptions.FindControl("pnlFrenchItemTemplate")).Visible = false;
                                ((Panel)fvMasterEnergyConsumptions.FindControl("pnlArabicDescription")).Visible = true;

                            }
                            catch (Exception exp)
                            {
                            }

                            break;
                        }

                }
                try
                {
                    if (tvMasterItems.SelectedNode != null && tvMasterItems.SelectedNode.ChildNodes.Count > 0)
                        ((Button)fvMasterEnergyConsumptions.FindControl("DeleteButton")).Enabled = false;
                }
                catch (Exception exc)
                { 
                }
            }
        }

        protected void fvMasterEnergyConsumptions_ItemInserting(object sender, FormViewInsertEventArgs e)
        {
            // Add the Parent Item to the Insert EventArgs if any node is selected
            if (((TreeView)fvMasterEnergyConsumptions.FindControl("tvParentItems_Insert")).SelectedNode != null)
                e.Values["ParentItemId"] = ((TreeView)fvMasterEnergyConsumptions.FindControl("tvParentItems_Insert")).SelectedNode.Value;
            else
                e.Values["ParentItemId"] = 0;

            // Add the Language code from Session object
            e.Values["LanguageCode"] = Session["LanguageCode"];
        }

        protected void fvMasterEnergyConsumptions_ItemInserted(object sender, FormViewInsertedEventArgs e)
        {
            // Refresh Items Table
            RefreshEnergyConsumptionMasterTable(0);

            // Build the main tree view
            BuildTree(tvMasterItems, 0);

            // Expand All tree nodes
            tvMasterItems.ExpandAll();
        }

        protected void fvMasterEnergyConsumptions_ItemUpdated(object sender, FormViewUpdatedEventArgs e)
        {
            // Refresh Items Table
            RefreshEnergyConsumptionMasterTable(0);

            // Build the main tree view
            BuildTree(tvMasterItems, 0);

            // Expand All tree nodes
            tvMasterItems.ExpandAll();
        }

        protected void fvMasterEnergyConsumptions_ItemUpdating(object sender, FormViewUpdateEventArgs e)
        {
            // Add the Parent Item to the Insert EventArgs if any node is selected
            if (((TreeView)fvMasterEnergyConsumptions.FindControl("tvParentItems_Edit")).SelectedNode != null)
                e.NewValues["ParentItemId"] = ((TreeView)fvMasterEnergyConsumptions.FindControl("tvParentItems_Edit")).SelectedNode.Value;
            else
                e.NewValues["ParentItemId"] = 0;

            // Add the Language code from Session object
            e.NewValues["LanguageCode"] = Session["LanguageCode"];
        }

        protected void btnAddItem_Click(object sender, EventArgs e)
        {
            // check if a node is selected form the Master Tree
            if (tvMasterItems.SelectedNode == null)
                hiddenSelectedNodeId.Value = "";
            else
                hiddenSelectedNodeId.Value = tvMasterItems.SelectedNode.Value;

            // Change Form View mode to Insert Item
            fvMasterEnergyConsumptions.ChangeMode(FormViewMode.Insert);
        }

        protected void tvParentItems_Insert_SelectedNodeChanged(object sender, EventArgs e)
        {
            string ParentItemName = ((TreeView)fvMasterEnergyConsumptions.FindControl("tvParentItems_Insert")).SelectedNode.Text;
            ((Label)fvMasterEnergyConsumptions.FindControl("lblParentItemName_Insert")).Text = ParentItemName;
        }

        protected void tvParentItems_Edit_SelectedNodeChanged(object sender, EventArgs e)
        {
            string ParentItemName = ((TreeView)fvMasterEnergyConsumptions.FindControl("tvParentItems_Edit")).SelectedNode.Text;
            ((Label)fvMasterEnergyConsumptions.FindControl("lblParentItem_Edit")).Text = ParentItemName;
        }

        protected void fvMasterEnergyConsumptions_ItemDeleted(object sender, FormViewDeletedEventArgs e)
        {
            // Refresh Items Table
            RefreshEnergyConsumptionMasterTable(0);

            // Build the main tree view
            BuildTree(tvMasterItems, 0);

            // Expand All tree nodes
            tvMasterItems.ExpandAll();
        }
    }
}